package com.valuedaas.schoolsafety.common.filter;

import com.valuedaas.schoolsafety.common.ErrorCodes;
import com.valuedaas.schoolsafety.common.enums.ProtectType;
import com.valuedaas.schoolsafety.controller.user.vo.User;
import com.valuedaas.schoolsafety.service.recources.InterfaceService;
import com.valuedaas.schoolsafety.util.WebUtil;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证用户是否有权限能访问某个接口
 */
@Component
@WebFilter(filterName = "permissionFilter", urlPatterns = "*.do")
@Order(3)
public class PermissionFilter extends OncePerRequestFilter {

    static final Logger LOG = LoggerFactory.getLogger(PermissionFilter.class);

    @Autowired
    private InterfaceService interfaceService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
                                    FilterChain chain) throws ServletException, IOException {
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        if (url.startsWith("/") && url.length() > 1) {
            url = url.substring(1);
        }
        if(WebUtil.isSwaggerResources(url)){ //跳过swagger 资源
            chain.doFilter(httpRequest, httpResponse);
            return;
        }
        if (WebUtil.isNoNeedPermission(url)) { //跳过不需要验证的资源
            chain.doFilter(httpRequest, httpResponse);
            return;
        }
        try {
            Document interDoc = interfaceService.findInterface(url);
            if (interDoc == null) {
                LOG.warn("该接口没有配置:{}", url);
                WebUtil.responseJson(ErrorCodes.RESOURCE_NOT_EXIST, "该接口没有配置", httpResponse);
                //看情况，未配置的可以访问，还是不可以访问
//                chain.doFilter(httpRequest, httpResponse);
                return;
            }
            String protect = interDoc.getString("protect");
            if (protect.equals(ProtectType.NEED_PERMISSION)) {
                User user = WebUtil.getSessionUser();
                boolean access = interfaceService.accessAuth(user, interDoc.getObjectId("_id").toHexString());
                if (!access) {
                    LOG.warn("denied [{}] access resource [{}]", user.getUsername(), url);
                    WebUtil.responseJson(402, "您无操作权限", httpResponse);
                    return;
                }
                chain.doFilter(httpRequest, httpResponse);
            }
        } catch (Exception e) {
                LOG.error("权限过滤器异常", e);
            WebUtil.responseJson(ErrorCodes.UNKNOW_ERROR, "未知错误", httpResponse);
        }
    }
}
